<?php
/**
 * @package base
 */

/**
 * Class handling Ajax calls.
 *
 */
class AjaxHandle {
	/**
	 * Error text which is going to be written into the output.
	 */
	private static $errorText = "";
	
	/**
	 * Trigger error.
	 */
	private static function inError($errorText, $exception) {
		self::$errorText .= $errorText;
		throw $exception;
	}
	/**
	 * Method used when hiding or deleting offers.
	 * @param string $baseQuery - base sql query
	 * @param stdClass $received - received JSON data parsed into an object
	 */
	private static function hideOrDeleteOffer($baseQuery, stdClass $received) {
		$info = SiteContext::getSiteContext();
		$dbConnector = $info->getDBConnector();
		
		$whereQuery = "";
		$sum = 0;
		foreach ($received->data as $value) {
			$offerId = intval($value);
			++$sum;
			if ($whereQuery == "") {
				$whereQuery .= " where (offers.id = ".$offerId; // TODO use constant for offers
			} else {
				$whereQuery .= " or offers.id = ".$offerId;
			}
		}
		if ($sum > 0) {
			$whereQuery .= ") limit $sum";
			$dbConnector->query($baseQuery.$whereQuery);
		}
	}
	
	/**
	 * Major method processing diverse ajax calls.
	 */
	public static function processAjaxCall() {
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		$logger = Logger::getLogger();
		$dbConnector = $info->getDBConnector();
		
		sleep(1); // TODO this should be removed in production environment
		
		try {
			$var = @$_REQUEST['ajaj'];
			$received = json_decode($var);
			
			switch($received->action) {
				case "addOffersToII":
					foreach ($received->data as $value) {
						$info->addInterestedInItem((int)$value);
					}
				break;
				case "removeOffersFromII":
					foreach ($received->data as $value) {
						$info->removeInterestedInItem((int)$value);
					}
				break;
				case "setCountOfPagesForListView":
					$info->setCountOfItemsInListView((int)$received->data);
				break;
				case "setCountOfPagesForThumbView":
					$info->setCountOfItemsInThumbView((int)$received->data);
				break;
				case "deleteOffers":
					if (Policy::hasCurrentUserAtLeastFullRights()) {
						self::hideOrDeleteOffer("delete from offers", $received);
					} else {
						self::inError($cm->get("30037"), new ExceptionBadPrivileges("Cannot delete offer"));
					}
				break;
				case "hideOffers": // TODO remove this redundancy with previous case statement
					if (Policy::hasCurrentUserAtLeastFullRights()) {
						self::hideOrDeleteOffer("UPDATE `eaiis`.`offers` SET `status` = 'hidden'", $received);
					} else {
						self::inError($cm->get("30037"), new ExceptionBadPrivileges("Cannot hide offer"));
					}
				break;
				case "deleteUsers":
					if (Policy::hasCurrentUserAtLeastFullRights()) {
						$whereQuery = "";
						$sum = 0;
						$isNotProblem = true;
						foreach ($received->data as $value) {
							++$sum;
							$userId = intval($value);
							$res = $dbConnector->query("select count(*) from offers where agentId = ".$userId);
							$arr = mysql_fetch_row($res);
							if ($arr[0] == 0) {
								// user with id agentId hasn't assigned any offer
								if ($whereQuery == "") {
									$whereQuery .= " where (users.id = " . $userId; // TODO use constant for offers
								} else {
									$whereQuery .= " or users.id = ".$userId;
								}
							} else {
								// user has assigned offer -> trigger error
								$res = $dbConnector->query("select login from users where id = ".$userId);
								$arr = mysql_fetch_row($res);
								if (!$isNotProblem) {
									// write "Error" to the box
									self::$errorText .= BR."<b>".$cm->get("10006").":</b> ";
								} else {
									$isNotProblem = false;
								}
								self::$errorText .= $cm->get("30203", $arr);
							}
						}
						if ($isNotProblem && $sum > 0) {
							$whereQuery .= ") limit $sum";
							$dbConnector->query("delete from users".$whereQuery);
						} else {
							self::$errorText .= BR."<b> ".$cm->get("10006").":</b> ".$cm->get("30204");
							self::inError("", new ExceptionIllegalState("cannot delete users with assigned offers."));
						}
					} else {
						self::inError($cm->get("30208"), new ExceptionBadPrivileges("Cannot delete user"));
					}
				break;
				default:
					header( "HTTP/1.1 400 Bad Request" );
					header( "Status: 400 Bad Request" );
			}
		} catch (Exception $e) {
			$logger->error($e->getTraceAsString());
			header( "HTTP/1.1 400 Bad Request" );
			header( "Status: 400 Bad Request" );
			echo self::$errorText;
		}
	}
}
?>